// components/chat_bar/chat_bar.js
let query={}
var rm = wx.getRecorderManager();
const radioTime = 5000
var touchTime = 0;
var keyboardHeight = 315;
var raduoState = "Stop"
const CONTEXT = require('../../utils/public_var')
const OCRFun = require('../../pages/fun_js/ocr.js')
const GoodsFun = require('../../pages/fun_js/goods.js')

 var session = null
function isEmptyObj(obj) {
  return typeof obj === 'object' && Object.keys(obj).length === 0;
}

Component({
 

  /**
   * 组件的属性列表
   */
  properties: {
    funSupport:{
      value:{},
      type:Object,
    observer:function (newData,oldData) {
      if(!isEmptyObj(newData)){
      var menuLists=[]
      var type = false;
      menuLists.push(newData.imageOCR)
      menuLists.push(newData.fileupload)
      menuLists.push(newData.soundupload)
      menuLists.push(newData.imageupload)
 
      menuLists.forEach(item=>{
        // console.log(item.available)
        if(item?.available == "1"){
          type = true
        }
       
      })  
        this.setData({
          funSupport:newData,
          funMenuList:menuLists,
          noFunMenu:type,
          adjustposition:!type,
          ifSend:type?false:newData.textInput=="1"?true:false
        })
        if(newData.textInput.available == "0"){
          this.getBarHeight()
        }
        

      

      }
    }
    },
    inputFocus:{
      value:false,
      type:Boolean,
    },
    totalCount:{
      value:0,
      observer:function(newData,oldData){
        console.log(newData)
        this.setData({
          totalCount:newData
        })
      }
    }
  
  },
  lifetimes:{
    created(){
      query = wx.createSelectorQuery().in(this);
       session = wx.createVKSession({
        version:'v1',
        track: {
         OCR: { mode: 2 } // mode: 1 - 使用摄像头；2 - 手动传入图像
       },
     })
   },
   
   
   ready(){
     var that = this
     wx.getSystemInfo({
      success: function (res) {
      
       let  windowHeight = res.windowWidth; // 获取页面可区域的
       let oneLine = windowHeight/13
       that.setData({
         funImgWidht:oneLine*2,
         marleft:oneLine
       })
        
       
      }
    });
    if(session!=null){
    console.log(session+"----")
     session.on('updateAnchors', anchors => {
        var data  = "".concat(anchors.map(anchor=>anchor.text))
        console.log("OCR 检测到了")
        console.log(data)
        this.setData({
          OCR_text:data
        })
       
      })
    }
    
     
   },
   detached(){
     console.log("session-detached")
     if(session!=null){
     session.stop()
     session.off("updateAnchors")
     session.destroy()
     }
   }
   
  },

  /**
   * 组件的初始数据
   */
  data: {
    ifSend:false,
    noFunMenu:false,
    input_tx:'',
    funMenuList:[],
    audio_img:'/images/audio.png',
    inputType:'text',
    clickType:'text',
    OCR_text:'',
    audio_view:'audio_view',
    funViewHeight:0,
    funImgWidht:0,
    upImgList:[],
    adjustposition:false,
    ocr:{
      faceImgUrl: '',
      faceImgWidth: 0,
      faceImgHeight: 0,
      faceImgOriginWidth: 0,
      faceImgOriginHeight: 0,
    }
  },

 


  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 打开语音监听
     */
    recordListener(){
      var that = this
     
      rm.onStart((e)=>{
       
        raduoState = "Start"
 
      })
    
      rm.onStop((e)=>{

        raduoState = "Stop"
     
        that.setData({
          audio_view:'audio_view'
        })
        if(e.duration<1000){
          wx.showToast({
            title: '说话时间太短',
            icon:'error',
          })

        }else{
          console.log(e)
          this.triggerEvent("record",e)
        }
      })
      rm.onRecognize = function(res) {
      
    }
      rm.onError((e)=>{
        raduoState = "Error"
        console.log("onError")
        console.log(e)
       
      })
    },
  /**
   * 切换语音输入框
   */
    audiofun(){
      this.recordListener()
      this.getBarHeight()
      if(this.data.inputType == 'text'){
        wx.getSetting({
          success: function (t) {
        
            if(t.authSetting["scope.record"]){
            }else{
              wx.authorize({
                scope: 'scope.record',
                success (res) {
                 
                },
                fail(res){
                  wx.showModal({
                    title: '提示',
                    content: '请点击右上角设置开启麦克风',
                    complete: (res) => {
                     
                    }
                  })
                }
              })
            } 
          }
        });
        this.setData({
          inputType:'audio',
          ifSend:false,
          input_tx:'',
          clickType:'audio',
          audio_img:'/images/jianpan.svg',
          inputFocus:false
        })
      }else{
        this.setData({
          inputType:'text',
          clickType : "text",
          audio_img:'/images/audio.png',
        })
      }

     

    },
  /**
   * 点击发送按钮
   */
    sendTextMsg(e){
      this.hintTip()
      // this.triggerEvent("TextEvent",this.data.upImgList)
      // this.triggerEvent("TextEvent",{"imgList":this.data.upImgList})
      // 文字或者图文
      if(this.data.clickType == "text"||this.data.clickType == "IMG-TEXT"){
      this.triggerEvent("TextEvent",{"imgList":this.data.upImgList,
      "type":"Identifyingobjects"})}
      else if(this.data.clickType == 'OCR'){
        if(this.data.OCR_text==""){
          wx.showToast({
            title: '文字识别异常，请更换图片',
            icon: "none"
          })
          return
        }
      //  OCR
         
          this.triggerEvent("TextEvent",{"imgList":this.data.upImgList,
          "msg":this.data.OCR_text,
          "type":"OCR"})
      }
    },
   /**
   * 上传数学图片
   */
    sendImgMsg(){
      this.triggerEvent("ImgEvent")
    },
    
    lineChange(e) {
      this.getBarHeight()
    },
    initInputTx(){
      this.setData({
        input_tx:'',
        ifSend:false,
        upImgList:[]
      })
    },
   
    inputChangetx: function (e) {
   
      if(e.detail.cursor>0){
       this.setData({
        ifSend:true
       })
      }
     else if (e.detail.cursor > 300) {
     
        wx.showModal({
          title: '问题太长',
          content: '主公，最长输入不超300个字符',
          complete: (res) => {
            if (res.cancel) {}
            if (res.confirm) {}
          }
        })
        return
      }else{
        this.setData({
          ifSend:false
         })
      }
      var text = e.detail.value
      this.setData({
        input_tx: text
      })
      this.triggerEvent('input',{data:text})

    },
    getBarHeight(){
      var that = this
      let query = wx.createSelectorQuery().in(this);
      query.select('#bottom').boundingClientRect()
      query.exec(function (res) {
        const view1Height = res[0].height;
        that.triggerEvent('lineChange',{data:view1Height})
      })
    },
    touchStart(e){
      if(raduoState !='Start'){
        wx.vibrateShort({})
        this.setData({
          audio_view:'audio_viewafter'
        })
        rm.start({
          duration:5000,
          sampleRate:8000,
          numberOfChannels:1,
          format:'wav'
        })
        
      }
     
    },
    touchEnd(e){
   
     rm.stop({})
     raduoState = "Stop"
      this.setData({
        audio_view:'audio_view'
      })
    },
    getInputFocus(res){
      // 获取到焦点时
      
      
      keyboardHeight = res.detail.height
      this.setData({
        funViewHeight:this.data.noFunMenu?res.detail.height:0,
        inputFocus:true
      
      })
      this.getBarHeight()
    },
    showFunLayout(){
      var that = this
      if(this.data.inputFocus){
         //获得焦点了
         wx.hideKeyboard()
      }else{
        if(that.data.funViewHeight==0){
          that.setData({
            funViewHeight:that.data.noFunMenu?keyboardHeight:0
          })
          that.getBarHeight()
      }else{
        this.setData({
          funViewHeight:0
        })
        that.getBarHeight()
      }
      }
      
    },
    hintAll(){
    
      this.setData({
        funViewHeight:0,
      })
      
      this.getBarHeight()
     
    },
    bindDBlur(res){
     
      this.setData({
        inputFocus:false
      })
    },
    /**
     *点击funSupport 
     * @param {} res 
     */
    menuClick(res){
      console.log(res)
      if(res.currentTarget.dataset.item.iconName == "图片处理"){
        //Math 图片
        // this.data.clickType = "MATH-IMG"
        this.sendImgMsg()
      }else if(res.currentTarget.dataset.item.iconName == "文字识别"){
        //OCR
       
        this.data.clickType = "OCR"
        const app  =getApp()
        OCRFun.shibiewenzi(this,app,session)
      }else{
        // GoodsFun.  图文
        this.data.clickType = "IMG-TEXT"
        this.sendUpImgMsg()
      }

    },
    sendUpImgMsg(){
      this.triggerEvent("sendUpImgMsg")
    },
    /**
     * 发送语音消息
     * @param {*} e 
     */
    record(e){
      this.triggerEvent("record",e)
    },
    hintTip(){
      this.hintAll()
      wx.hideKeyboard()
    },
    /**
     * 删除图片
     */
    delete_img(index){
      console.log(index)
      var imgList = this.data.upImgList;
      imgList.pop(index)
      this.setData({
        upImgList:imgList
      })
      this.getBarHeight()
    },
    // 选择图片后渲染到页面中
    addUpImg(img){
      var imgs = this.data.upImgList;
      imgs.push(img)
      this.setData({
        upImgList:imgs,
        ifSend:true
      })
      this.getBarHeight()
    }
   

   
  }

  
})
